package com.dataView.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtile {
	
	public static <T> void writeFileList(List<T>  obj, String path) throws Exception {
		File file = new File(path);
        //如果没有文件就创建
        if (!file.isFile()) {
            file.createNewFile();
        }
		FileUtils.writeLines(file,obj);
        System.out.println("===================End=====================");
	}
	public static void writeFileJson(JSON json, String path) throws Exception {
		File file = new File(path);
		//如果没有文件就创建
		if (!file.isFile()) {
			file.createNewFile();
		}
		FileUtils.writeStringToFile(file,json.toJSONString(),"UTF-8");
		System.out.println("===================End=====================");
	}

	/**
	 * 判断文件是否存在 并 返回数据
	 * @param path
	 * @return
	 */
	public static List<String> checkFileExistenceStatue(String path) throws IOException {
		List<String> oldData = new ArrayList<>();
		File file = new File(path);
		if(file.length() != 0){
			oldData = FileUtils.readLines(file, "UTF-8");
		}
		return oldData;
	}

	/**
	 * 删除老文件 创建新文件并写入数据
	 * @param path
	 * @param data
	 */
	public static <T> void deleteFileAndCreatNewFile(String path, List<T> data) throws IOException {
		if(!CollectionUtils.isEmpty(data)){
			FileUtils.deleteQuietly(new File(path));
			FileUtils.writeLines(new File(path),data);
		}
	}


}
